<?php

namespace app\mobile\controller;

use think\Controller;
use app\api\model\User as UserModel;

class Wechatconnect extends Controller
{
	private $TOKEN = '';
	private $WXST1 = '内蒙古伊生泰健康汇';
	private $WXDES1 = '点击领取---我的订单';
	private $WXIMG1 = 'https://ystmall.dieya.net/assets/firstImg22.jpg';
	// 记得加参数
	private $WXURL1 = 'https://ystmall.dieya.net/index.php?s=/mobile/perpage/orderdes';
	// 公众号返回的消息体
    public function index()
    {
		$this->TOKEN = Config('TOKEN');
		
		
		
		$xml = file_get_contents('php://input');
		$wxbackData = $this->xmlToArray($xml);
		
		$this->logger("---------------------------：_GET \r\n". print_r($_GET, true));
		$this->logger("---------------------------：wxbackData \r\n".print_r($wxbackData, true));
		
		if (!isset($_GET['echostr'])) {
			$this->responseMsg($wxbackData);
			
			// 如果存在openid，统一先进行注册或登录，因腾讯不再给头像昵称信息，故此处不用再注册了
			// if(isset($wxbackData['FromUserName'])){
			// 	$openId = $wxbackData['FromUserName'];
			// 	$wxFun = new \wechatFun(Config('appId'), Config('appSecret'));
			// 	$userInfo = $wxFun->get_user_info($openId);
			// 	$this->logger("---------------------------：userInfo \r\n". print_r($userInfo, true));
			// }
		}else{
		    $this->valid();
		}
    }
	
	// 将结果转化为数组
	private function xmlToArray($xml) {
	    $array = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
	    $json = json_encode($array);
	    $responseArray = json_decode($json, true);
	
	    return $responseArray;
	}
	
	// 记录日志
	private function logger($log_content)
	{
	    if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
	        sae_set_display_errors(false);
	        sae_debug($log_content);
	        sae_set_display_errors(true);
	    }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
	        $max_size = 1000000;
	        $log_filename = "wechatLog.xml";
	        if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
	        file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
	    }
	}
	
	//验证签名
	private function valid()
	{
	    $echoStr = $_GET["echostr"];
	    $signature = $_GET["signature"];
	    $timestamp = $_GET["timestamp"];
	    $nonce = $_GET["nonce"];
	    $token = $this->TOKEN;
	    $tmpArr = array($token, $timestamp, $nonce);
	    sort($tmpArr, SORT_STRING);
	    $tmpStr = implode($tmpArr);
	    $tmpStr = sha1($tmpStr);
	    if($tmpStr == $signature){
	        echo $echoStr;
	        exit;
	    }
	}
	
	//响应消息
	public function responseMsg($wxbackArr)
	{
		if(isset($wxbackArr['MsgType'])){
			$RX_TYPE = $wxbackArr['MsgType'];
			//消息类型分离
			switch ($RX_TYPE)
			{
				//sx响应各种事件
				case "event":
					$result = $this->receiveEvent($wxbackArr);
					break;
				// //sx响应文本消息
				// case "text":
				//    if (strstr($wxbackArr['Content'], "第三方")){
				// 		$result = $this->relayPart3("http://www.fangbei.org/test.php".'?'.$_SERVER['QUERY_STRING'], $postStr);
				// 	}else{
				// 		$result = $this->receiveText($wxbackArr);
				// 	}
				// 	break;
				// case "image":
				// 	$result = $this->receiveImage($wxbackArr);
				// 	break;
				// case "location":
				// 	$result = $this->receiveLocation($wxbackArr);
				// 	break;
				// //sx响应语音消息
				// case "voice":
				// 	$result = $this->receiveVoice($wxbackArr);
				// 	break;
				// case "video":
				// 	$result = $this->receiveVideo($wxbackArr);
				// 	break;
				// case "link":
				// 	$result = $this->receiveLink($wxbackArr);
				// 	break;
				default:
					$result = "unknown msg type: ".$RX_TYPE;
					break;
			}
			// $this->logger("---------------------------：result \r\n".$result);
			echo $result;
		}
	}
	
	//接收事件消息
	private function receiveEvent($wxbackArr){
		$content = "";
		if(isset($wxbackArr['Event'])){
			$EEE = $wxbackArr['Event'];
			switch ($EEE)
			{
				//用户关注后
				case "subscribe":
					$openId = $wxbackArr['FromUserName'];
					$screenId = str_replace("qrscene_","", $wxbackArr['EventKey']);
					if($screenId>0){
						$backArr = array();
						$backArr[] = array("Title"=>$this->WXST1,  "Description"=>$this->WXDES1, 
						"PicUrl"=>$this->WXIMG1, "Url" =>$this->WXURL1."/rid/".$screenId);
						
						$content = $backArr;
					}
					break;
				//取消关注
				case "unsubscribe":
					$result = "test test";
					break;
				// 已关注的扫码执行，则执行此处扫码事件
				case "SCAN":
					$openId = $wxbackArr['FromUserName'];
					$screenId = $wxbackArr['EventKey'];
					
					$backArr = array();
					$backArr[] = array("Title"=>$this->WXST1,  "Description"=>$this->WXDES1, 
					"PicUrl"=>$this->WXIMG1, "Url" =>$this->WXURL1."/rid/".$screenId);
					
					$content = $backArr;
					break;
				//CLICK，用户点击菜单后，有限执行此处再跳转
				case "subscribe":
					$result = "test test";
					break;
				//用户关注后
				case "subscribe":
					$result = "test test";
					break;
				//跳转链接
				case "VIEW":
				    $result = "test test";
				    break;
				//扫描第三方的二维码或条形码
				case "scancode_waitmsg":
				    $result = "test test";
				    break;
				default:
					$result = "unknown msg event: ".$EEE;
					break;
			}
			
		}
		
		// 发送图文消息
		if(is_array($content)){
		    if (isset($content[0]['PicUrl'])){
		        $result = $this->transmitNews($wxbackArr, $content);
		    }
			// 发送音频消息
			else if (isset($content['MusicUrl'])){
		        //$result = $this->transmitMusic($wxbackArr, $content);
		    }
		}
		// 发送文字消息
		else{
		    // $result = $this->transmitText($wxbackArr, $content);
		}
		return $result;
	}
	
	//回复图文消息
	private function transmitNews($object, $newsArray)
	{
		if(!is_array($newsArray)){
			return "";
		}
		$len = count($newsArray);
		
		$item_str = "";
		foreach ($newsArray as $item){
			$item_str .= "<item>
		      <Title><![CDATA[{$item['Title']}]]></Title>
		      <Description><![CDATA[{$item['Description']}]]></Description>
		      <PicUrl><![CDATA[{$item['PicUrl']}]]></PicUrl>
		      <Url><![CDATA[{$item['Url']}]]></Url>
		    </item>";
		}
		$result = "<xml>
		  <ToUserName><![CDATA[{$object['FromUserName']}]]></ToUserName>
		  <FromUserName><![CDATA[{$object['ToUserName']}]]></FromUserName>
		  <CreateTime>{$object['CreateTime']}</CreateTime>
		  <MsgType><![CDATA[news]]></MsgType>
		  <ArticleCount>{$len}</ArticleCount>
		  <Articles>
		    {$item_str}
		  </Articles>
		</xml>";
		return $result;
		
		// $itemTpl = "<item>
		// 	<Title><![CDATA[%s]]></Title>
		// 	<Description><![CDATA[%s]]></Description>
		// 	<PicUrl><![CDATA[%s]]></PicUrl>
		// 	<Url><![CDATA[%s]]></Url>
		// </item>";
		// $item_str = "";
		// foreach ($newsArray as $item){
		// 	$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
		// }
		// $xmlTpl = "<xml>
		// 	<ToUserName><![CDATA[%s]]></ToUserName>
		// 	<FromUserName><![CDATA[%s]]></FromUserName>
		// 	<CreateTime>%s</CreateTime>
		// 	<MsgType><![CDATA[news]]></MsgType>
		// 	<ArticleCount>%s</ArticleCount>
		// 	<Articles>$item_str</Articles></xml>";

		// $result = sprintf($xmlTpl, $object['FromUserName'], $object['ToUserName'], time(), count($newsArray));
		// return $result;
	}
}